// src/utils/websocket.js
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

let stompClient = null;
export function connectWebSocket(onMessage) {
  const socket = new SockJS('http://localhost:8081/ws');
  stompClient = new Client({
    webSocketFactory: () => socket,
    debug: str => console.log('[WS]', str),
    onConnect: () => {
      console.log('WebSocket connected');
      stompClient.subscribe('/topic/queueBatch', msg => {
        try {
          const data = JSON.parse(msg.body);
          onMessage(data);
        } catch (e) {
          console.error('JSON parse error', e);
        }
      });
    },
    onStompError: frame => console.error('STOMP Error', frame),
    onWebSocketClose: () => console.log('WebSocket closed'),
  });
  stompClient.activate();
}
export function disconnectWebSocket() {
  if (stompClient && stompClient.active) {
    stompClient.deactivate();
    console.log('WebSocket disconnected');
  }
}